package com.cy.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cy.server.config.security.component.JwtTokenUtil;
import com.cy.server.mapper.AdminRoleMapper;
import com.cy.server.mapper.RoleMapper;
import com.cy.server.pojo.*;
import com.cy.server.mapper.AdminMapper;
import com.cy.server.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cy.server.utils.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiShaoZhuo
 * @since 2021-04-26
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    AdminRoleMapper adminRoleMapper;

    /**
    * @Description: 登陆之后返回token
    * @Param: userName,passWord,request
    * @return:
    * @Author: LiShaoZhuo
    * @Date: 2021/4/26
    */
    @Override
    public RespBean login(String userName, String passWord, String code, HttpServletRequest request) {
        //从session中获取验证码
        String kaptcha = (String) request.getSession().getAttribute("kaptcha");
        if (StringUtils.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码输入有误，请刷新后再次输入！");
        }
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        //验证用户
        if (userDetails == null || !passwordEncoder.matches(passWord, userDetails.getPassword())){
            return RespBean.error("用户名或密码不正确");
        }
        if (!userDetails.isEnabled()){
            return RespBean.error("账号被禁用，请联系管理员");
        }
        //更新security用户登录对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return RespBean.success("登录成功！",tokenMap);
    }

    /**
    * @Description: 根据用户名获取用户
    * @Param: userName
    * @return:
    * @Author: LiShaoZhuo
    * @Date: 2021/4/26
    */
    @Override
    public Admin getAdminByUserName(String userName) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", userName)
                .eq("enabled", true));
    }

    /**
     * @Description: 根据id获取角色
     * @Param: adminId
     * @return:
     * @Author: LiShaoZhuo
     * @Date: 2021/4/29
     */
    @Override
    public List<Role> getRolesByAdminId(Integer adminId) {
        return roleMapper.getRolesByAdminId(adminId);
    }

    /**
     * @Description:  获取所有操作员
     * @Param:
     * @return:
     * @Author: LiShaoZhuo
     * @Date: 2021/4/30
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        return adminMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(),keywords);
    }

    /**
     * @Description: 更新操作员角色
     * @Param:
     * @return:
     * @Author: LiShaoZhuo
     * @Date: 2021/4/30
     */
    @Override
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId", adminId));
        Integer result = adminRoleMapper.addAdminRole(adminId,rids);
        if(result == rids.length){
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    /**
     * @Description: 更新用户密码
     * @Param:
     * @return:
     * @Author: LiShaoZhuo
     * @Date: 2021/5/10
     */
    @Override
    public RespBean updateAdminPassword(String oldPass, String pass, Integer adminId) {
        //通过id获取用户对象
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //密码解密后判断旧密码是否正确
        if (encoder.matches(oldPass, admin.getPassword())){
            //设置新密码
            admin.setPassword(encoder.encode(pass));
            int result = adminMapper.updateById(admin);
            if (result == 1){
                return RespBean.success("更新成功");
            }
        }
        return RespBean.error("更新失败");
    }

    /**
     * @Description: 更新用户头像
     * @Param:
     * @return:
     * @Author: LiShaoZhuo
     * @Date: 2021/5/11
     */
    @Override
    public RespBean updateAdminUserface(String url, Integer id, Authentication authentication) {
        //获取用户对象
        Admin admin = adminMapper.selectById(id);
        //设置用户头像
        admin.setUserFace(url);
        //更新用户
        int result = adminMapper.updateById(admin);
        if (result == 1){
            //获取全局对象
            Admin principal = (Admin) authentication.getPrincipal();
            principal.setUserFace(url);
            //更新头像
            SecurityContextHolder.getContext()
                    .setAuthentication(new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities()));
            return RespBean.success("更新成功",url);
        }
        return RespBean.error("更新失败");
    }
}
